package com.ybdz.scanner.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.ybdz.scanner.R;
import com.ybdz.scanner.api.ApiStore;
import com.ybdz.scanner.base.BaseActivity;
import com.ybdz.scanner.bean.DepositHistoryBean;
import com.ybdz.scanner.bean.InputBean;
import com.ybdz.scanner.bean.InputWeightBean;
import com.ybdz.scanner.event.ObjEvent;
import com.ybdz.scanner.utils.MyToast;
import com.ybdz.scanner.utils.SPUtils;
import com.ybdz.scanner.utils.SharedPreferenceUtil;
import com.ybdz.scanner.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ClassName: InputWeightActivity
 * @author: zhao
 * @Description: 录入重量
 * @date 2018/2/24 15:39
 */
public class InputWeightActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    LinearLayout mLlBack;
    @BindView(R.id.home)
    FrameLayout mHome;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.place)
    TextView mPlace;
    @BindView(R.id.factory)
    TextView mFactory;
    @BindView(R.id.specification)
    TextView mSpecification;
    @BindView(R.id.weight)
    EditText mWeight;
    @BindView(R.id.checked)
    CheckBox mChecked;
    @BindView(R.id.rl_box)
    FrameLayout mRlBox;
    @BindView(R.id.save)
    Button mSave;
    @BindView(R.id.cancel)
    Button mCancel;
    @BindView(R.id.ll)
    LinearLayout mLl;

    private String isConformity = "false";
    private InputBean.DataBean mData;
    private String scanResult;
    private double mActualWeight;
    private List<DepositHistoryBean> mList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weight_input);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        //粗糙的实现在Editext获取焦点的情况下，点击其他地方隐藏输入框
        mLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                mWeight.setCursorVisible(false);
            }
        });
        initData(mData);
        if (!String.valueOf(mActualWeight).equals("0.0")) {
            setHint();
        } else {
            mWeight.setText("0.0");
        }
    }

    @OnClick({R.id.ll_back, R.id.home, R.id.save, R.id.cancel, R.id.weight})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:                      //返回
                finish();
                break;
            case R.id.home:                         //返回首页
                startActivity(new Intent(InputWeightActivity.this, MainActivity.class));
                finish();
                break;
            case R.id.save:                         //保存，提交数据到服务器
                String weight = mWeight.getText().toString().trim();    //获取用户录入的重量信息
                if (Double.parseDouble(weight) == 0.0 || weight  == null){
                    MyToast.show(InputWeightActivity.this, "请输入重量");
                }else {
                    inputWeightApi(weight);
                }
                break;
            case R.id.cancel:                       //取消，关闭界面
                finish();
            case R.id.weight:                       //设置点击获取焦点，显示光标
                mWeight.setCursorVisible(true);
                break;
        }
    }

    /**
     * 提交重量的网络请求
     * @param weight
     */
    private void inputWeightApi(final String weight) {
        if (mChecked.isChecked() == true) {         //获取CheckBox的状态
            isConformity = "false";
        } else {
            isConformity = "true";
        }
        showLoading();
        ApiStore.commitWeight(scanResult,weight,isConformity).enqueue(new Callback<InputWeightBean>() {
            @Override
            public void onResponse(Call<InputWeightBean> call, Response<InputWeightBean> response) {
                if (response != null && response.isSuccessful()){
                    hideLoading();
                    //EventBus.getDefault().postSticky(new ObjEvent("depositHistory", mList));
                    MyToast.show(InputWeightActivity.this, "录入成功");
                    InputWeightActivity.this.finish();
                }else {
                    hideLoading();
                    onFail();
                }
            }

            @Override
            public void onFailure(Call<InputWeightBean> call, Throwable t) {
                    hideLoading();
                    onFailTimeOut();
            }
        });
    }


    //EvnentBus接收上一个界面传递过来的对象信息
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getEvent(InputBean depositEvent) {
        mData = depositEvent.getData();
        mActualWeight = mData.getActualWeight();
    }

    //EvnentBus接收上一个界面传递过来的对象信息
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getScanResult(ObjEvent responeEvent) {
        if (responeEvent.getId().equals("scanResult")) {
            scanResult = (String) responeEvent.getObj();
        }
    }

    /**
     * 设置数据
     *
     * @param data
     */
    private void initData(InputBean.DataBean data) {
        mName.setText("品名：" + data.getProductName());
        mPlace.setText("原产地：" + data.getOrigin());
        mFactory.setText("工厂厂号：" + data.getFactoryNumber());
        mSpecification.setText("规格：" + data.getSpecification());
    }

    /**
     * 当重量不为null时，提示用户
     */
    private void setHint() {
        final String isQualified = mData.getIsQualified();
        new QMUIDialog.MessageDialogBuilder(InputWeightActivity.this)
                .setTitle(UIUtils.getString(R.string.hint))
                .setMessage(UIUtils.getString(R.string.dialog))
                .addAction(UIUtils.getString(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        InputWeightActivity.this.finish();
                    }
                })
                .addAction(0,UIUtils.getString(R.string.confirm), QMUIDialogAction.ACTION_PROP_NEGATIVE,new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        double actualWeight = mData.getActualWeight();
                        mWeight.setText(String.valueOf(actualWeight));
                        if (isQualified.equals("false")) {
                            mChecked.setChecked(true);
                        } else {
                            mChecked.setChecked(false);
                        }
                        dialog.dismiss();
                    }
                })
                .show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
